package mailsender

import org.apache.commons.lang.RandomStringUtils

class SignUpService {

    def springSecurityService
    def sendMailGateway

    def signUp(def params) {

        log.debug(params?.dump())
        // check for user
        def user = User.findByUsername(params?.email)

        if (user) {
            throw new Exception('User Already Exists')
        }

        user = new User(username: params?.email,
                password: springSecurityService.encodePassword(RandomStringUtils.randomAlphanumeric(30)),
                validationPhrase: RandomStringUtils.randomAlphanumeric(30)).save(failOnError : true, flush: true)

        if (user && !user?.hasErrors()) {
            def role = Role.findByAuthority('ROLE_USER')

            new UserRole(role: role, user:  user).save(failOnError: true, flush: true)

            user.save(failOnError : true, flush: true)

            // send verification email
            sendVerificationEmail(user)

            // log user into application - this creates a session
            springSecurityService.reauthenticate(user.username, user.password)

        }
    }


    def sendVerificationEmail(User user) {

        def map = [:]

        map.user = user
        map.subject = "Welcome to JTs Mail Sender App"
        map.template = "/email-templates/verifyAccount"
        map.model = [validationPhrase: user.validationPhrase, now: new Date()]

        log.info('Sending Mail Request to SI Gateway')

        sendMailGateway.asyncMailSender(map)
    }
}
